<?php
/**
 * 微信支付
 * User: shenyvlin
 * Date: 2019/3/5
 * Time: 10:10
 */
namespace app\api\controller\pay;

use think\facade\Config;
class Wxpay{
    protected $config;
    public function __construct()
    {
        $this->config = [
            'appid' => Config::get('app.wxpay.appid'),
            'mch_id' => Config::get('app.wxpay.mch_id'),
            'api_key' => Config::get('app.wxpay.api_key'),
            'pay_notify_url' => Config::get('app.wxpay.pay_notify_url'),
            'refund_notify_url' => Config::get('app.wxpay.refund_notify_url'),
        ];
    }

    public function getPrePayOrder($body, $out_trade_no, $total_fee, $notify_url=''){
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $onoce_str = $this->getRandChar(32);
        $data["appid"] = $this->config["appid"];
        $data["body"] = $body;
        $data["mch_id"] = $this->config['mch_id'];
        $data["nonce_str"] = $onoce_str;
        $data["notify_url"] = $notify_url? $notify_url: $this->config['pay_notify_url'];
        $data["out_trade_no"] = $out_trade_no;
        $data["spbill_create_ip"] = $this->get_client_ip();
        $data["total_fee"] = $total_fee;
        $data["trade_type"] = "APP";
        $s = $this->getSign($data);
        $data["sign"] = $s;

        $xml = $this->arrayToXml($data);
        $response = $this->postXmlCurl($xml, $url);

        //将微信返回的结果xml转成数组
//        return $this->domnode_to_array($response);
        return $this->xmlToObject($response);
    }

    //执行第二次签名，才能返回给客户端使用
    public function getOrder($prepayId){
        $data["appid"] = $this->config["appid"];
        $data["noncestr"] = $this->getRandChar(32);;
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['mch_id'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->getSign($data);
        $data["sign"] = $s;

        return $data;
    }

    /*
        生成签名
    */
    function getSign($Obj)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[strtolower($k)] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".$this->config['api_key'];
        //签名步骤三：MD5加密
        $result_ = strtoupper(md5($String));
        return $result_;
    }

    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

    //数组转xml
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    //post https请求，CURLOPT_POSTFIELDS xml格式
    function postXmlCurl($xml,$url,$second=30)
    {
        //初始化curl
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }

    /*
        获取当前服务器的IP
    */
    function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }

    //将数组转成uri字符串
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            $buff .= strtolower($k) . "=" . $v . "&";
        }
        $reqPar = '';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

    public function xmlToObject($xmlStr)
    {
        if (!is_string($xmlStr) || empty($xmlStr)) {
            return false;
        }
        // 由于解析xml的时候，即使被解析的变量为空，依然不会报错，会返回一个空的对象，所以，我们这里做了处理，当被解析的变量不是字符串，或者该变量为空，直接返回false
        $postObj = simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        $postObj = json_decode(json_encode($postObj));
        //将xml数据转换成对象返回
        return $postObj;
    }

    public function payCallback()
    {
        $postXml = file_get_contents("php://input");    // 接受通知参数；
        $postObj = $this->xmlToObject($postXml);      // 调用解析方法，将xml数据解析成对象
        $sign = $postObj->sign;

		//验证签名
		$data_sign = $this->getSign($postObj); 
		if ($sign != $data_sign){
			echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>'; 
			trace('签名失败: 本地签名 '.$data_sign."，返回签名 ".$sign, 'wx_notify');
			return false;
		}

        if ($postObj->return_code == "SUCCESS" && $postObj->result_code == "SUCCESS") {
            return $postObj;
        }
        else{
            trace($postObj,'wxNotify');
            return false;
        }
    }

    /* ------------------------------------------------------ 退款 ------------------------------------------------------ */

    /**
     * 微信退款(POST)
     * @param string(28) $transaction_id 	在微信支付的时候,微信服务器生成的订单流水号,在支付通知中有返回
     * @param string $out_refund_no 		商品简单描述
     * @param string $total_fee 			微信支付的时候支付的总金额(单位:分)
     * @param string $refund_fee 			此次要退款金额(单位:分)
     * @param string $notify_url 			通知回调地址
     * @return array						
     */
	public function refund($transaction_id,$out_refund_no,$total_fee,$refund_fee, $notify_url=''){
		$config = $this->config;
		//退款参数
		$refundorder = array(
			'appid'			=> $config['appid'],
			'mch_id'		=> $config['mch_id'],
			'nonce_str'		=> $this->getRandChar(32),
			'transaction_id'=> $transaction_id,
			'out_refund_no'	=> $out_refund_no,
			'total_fee'		=> $total_fee,
			'refund_fee'	=> $refund_fee,
			'notify_url'	=> $notify_url ? $notify_url: $config['refund_notify_url'],
		);
		$refundorder['sign'] = $this->getSign($refundorder);
		//请求数据,进行退款
		$xmldata = $this->arrayToXml($refundorder);
		$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
		$res = $this->curl_post_ssl($url, $xmldata);
		// file_put_contents('log3.txt',$res,FILE_APPEND);
        if(!$res){
			return array('status'=>0, 'msg'=>"Can't connect the server" );
        }
		// 这句file_put_contents是用来查看服务器返回的结果 测试完可以删除了
		$content = $this->xmlToObject($res);
		return $content;
    }

    /**
	 * 微信支付退款发起请求
	 */
	protected function curl_post_ssl($url, $xmldata, $second=30,$aHeader=array()){
		$config = $this->config;
		
		$ch = curl_init();
		//超时时间
		curl_setopt($ch,CURLOPT_TIMEOUT,$second);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
		//这里设置代理，如果有的话
		//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
		//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
		curl_setopt($ch, CURLOPT_SSLVERSION, 1);
		
		//默认格式为PEM，可以注释
		curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLCERT, $config['api_cert']);
		//默认格式为PEM，可以注释
		curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
		curl_setopt($ch,CURLOPT_SSLKEY, $config['api_cert_key']);
		
		//curl_setopt($ch,CURLOPT_CAINFO,$config['rootca']);
	 
		if( count($aHeader) >= 1 ){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
		}
	 
		curl_setopt($ch,CURLOPT_POST, true);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$xmldata);
		$data = curl_exec($ch);
		if($data){
			curl_close($ch);
			return $data;
		}else { 
			$error = curl_errno($ch);
			echo "call faild, errorCode:$error\n"; 
			curl_close($ch);
			return false;
		}
    }

    public function refundCallback()
    {
        $postXml = file_get_contents("php://input");    // 接受通知参数；
        $postObj = $this->xmlToObject($postXml);      // 调用解析方法，将xml数据解析成对象

		//验证签名
		$decryptXml = $this->decryptData($postObj->req_info, config('api_key'));
		$orderData = $this->xmlToObject($decryptXml);

        if ($orderData->return_code == "SUCCESS" && $orderData->result_code == "SUCCESS") {
            return $orderData;
        }
        else{
            trace($orderData,'refundCallback');
            return false;
        }
    }
    
    /**
	 * decrypt data
	 * @param string $encryptData
	 * @param string $md5LowerKey
	 * @return string | FALSE
	 */
	public function decryptData(string $encryptData, string $Key = '')
	{
		//1. base64_decode
		// openssl_decrypt only accept base64 input param
		//2. md5 original key
		$md5LowerKey = strtolower(md5($Key));
		//3. decrypt AES ECB
		$decrypted = \openssl_decrypt($encryptData, "AES-256-ECB", $md5LowerKey);
		return $decrypted;
	}
    

}